import os,sys
import pytest
import time
from pytest_jsonreport.plugin import JSONReport


#1、Terminal里面执行命令，需要用下面的方式将rainbow加入环境变量
#2、部署到服务器上，也需要用这种方式加入环境变量，python run.py smoke，python run.py "smoke and pre"
from common.log import Log

base_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0,base_dir)

#从当前工程中导入的模块必须写在加入环境变量之后
from conf.config import case_path,report_path,email_content,dingding_content
from common import send_message, const


class RunCase:
    report_html = os.path.join(report_path,"report.html")
    report_title = "rainbow接口自动化测试报告 "
    plugin = JSONReport()
    dingding_group="qa"
    # dingding_group="qa","dev"
    #服务器上命令行运行，python run.py smok
    # def get_argv(self):
    #     if len(sys.argv)>1:
    #         tag=sys.argv[1].strip()
    #         if tag=="all":#jenkin不太智能，无法传空字符串
    #             return []
    #         return ['-m',tag]
    #     return []
    # 改进：python run.py --tag=xxx --env=xxx
    def get_argv(self):
        cmd_list = []
        for arg in sys.argv:
            if '--env=' in arg:
                env=arg.split('=')[-1]
                if env!='default':
                    const.cur_env = env
                # const.cur_env=env if env!='default'
                Log.debug("当前测试环境：{}",const.cur_env)
            if '--tag=' in arg:
                tag=arg.split('=')[-1]
                cmd_list=['-m',tag] if tag!='all' else cmd_list
        return cmd_list


    def run_case(self):
        command=["-vs",case_path,"--pytest_report",self.report_html,"--pytest_title",
             self.report_title,'--json-report-file=none']
        command.extend(self.get_argv())
        pytest.main(command,plugins=[self.plugin])
        summary = self.plugin.report.get("summary")
        self.total = summary.get("total", 0)
        self.passed = summary.get("passed", 0)
        self.failed = summary.get("failed", 0)
        self.error = summary.get("error", 0)
        self.skipped = summary.get("skipped", 0)
    def send_report(self):
        #钉钉
        content  = dingding_content % (self.total,self.passed,self.failed,self.error,self.skipped)
        send_message.DING.send_more_group(content,self.dingding_group,at_all=True)
        # d = send_message.DING("qa")
        # d.send_dd_msg(dingding_content,at_all=True)
        #邮件
        eamail_content  = email_content % (self.total,self.passed,self.failed,self.error,self.skipped)
        subject = self.report_title + time.strftime("%Y-%m-%d %H:%M:%S")
        send_message.send_mail(subject,eamail_content,self.report_html)
    @classmethod
    def main(cls):
        obj=cls()
        obj.run_case()
        obj.send_report()
if __name__ == '__main__':
    RunCase.main()


